package com.wmh.baseservice.merchant.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wmh.baseservice.common.annotation.parameterverify.ParameterVerify;
import com.wmh.baseservice.common.utils.CommUtil;
import com.wmh.baseservice.common.utils.DateFormatTemplate;
import com.wmh.baseservice.common.utils.UUIDUtil;
import com.wmh.baseservice.common.utils.encrypt.Base64Util;
import com.wmh.baseservice.common.utils.page.pojo.PageInfo;
import com.wmh.baseservice.common.utils.page.pojo.PageResult;
import com.wmh.baseservice.common.utils.page.util.PageUtil;
import com.wmh.baseservice.common.utils.returnbody.ResultCodeInfo;
import com.wmh.baseservice.common.utils.returnbody.ReturnBody;
import com.wmh.baseservice.merchant.pojo.MerchantActivity;
import com.wmh.baseservice.merchant.pojo.vo.RegisterPeopleDetailVO;
import com.wmh.baseservice.merchant.service.MerchantActivityService;
import com.wmh.baseservice.user.pojo.UsActivityRegister;
import com.wmh.baseservice.user.pojo.UsInfo;
import com.wmh.baseservice.user.service.UsActivityRegisterService;
import com.wmh.baseservice.user.service.UsInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.sql.Date;
import java.text.ParseException;
import java.time.ZonedDateTime;
import java.util.List;

/**
 * @author wmh generator
 * @since 2022-04-08
 */
@Api(tags = "商家端-活动相关接口")
@RestController
@RequestMapping(value = "merchant/merchantActivity", produces = "text/plain;charset=utf-8")
public class MerchantActivityController {

    @Resource
    private MerchantActivityService merchantActivityService;
    @Resource
    private HttpServletRequest request;
    @Resource
    private UsActivityRegisterService usActivityRegisterService;
    @Resource
    private UsInfoService usInfoService;

    @ApiOperation("活动列表")
    @PostMapping("list")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String list(PageInfo pageInfo, Integer sort, String title, Integer status, String createTimeScope) {
        Long merchantId = (Long) request.getAttribute("id");
        // 设置分页排序规则
        PageUtil.setPageSortRoles(pageInfo, sort, "create_time");
        //执行分页辅助工具
        PageResult<MerchantActivity> pageResult = new PageUtil<MerchantActivity>(pageInfo).startPage((page, queryWrapper) -> {
            queryWrapper.eq(MerchantActivity.MERCHANT_ID, merchantId);
            if (CommUtil.checkNull(title)) {
                queryWrapper.like(MerchantActivity.TITLE, title);
            }
            if (CommUtil.checkNull(status)) {
                queryWrapper.eq(MerchantActivity.STATUS, status);
            }
            if (CommUtil.checkNull(createTimeScope)) {
                List<String> list = JSON.parseArray(createTimeScope, String.class);
                queryWrapper.between(MerchantActivity.CREATE_TIME, list.get(0), list.get(1));
            }
            merchantActivityService.page(page, queryWrapper);
        });
        return ReturnBody.success(pageResult);
    }

    @ApiOperation("添加或修改活动")
    @PostMapping("add")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String add(Long id, String title, String overview, String lat, String lng, String content, Integer registerCount, String address,
                      Integer hasCost, BigDecimal cost, String banner, String startTime, String endTime, Long urlId) throws ParseException {
        Long merchantId = (Long) request.getAttribute("id");
        ZonedDateTime startDateTime = DateFormatTemplate.paresDate(startTime).atZone(DateFormatTemplate.ZONE_SHANGHAI);
        ZonedDateTime endDateTime = DateFormatTemplate.paresDate(endTime).atZone(DateFormatTemplate.ZONE_SHANGHAI);
        MerchantActivity merchantActivity = new MerchantActivity().setTitle(title).setOverview(overview).setLat(lat).setLng(lng)
                .setContent(content).setRegisterCount(registerCount).setHasCost(hasCost).setCost(cost)
                .setOpenTime(Date.from(startDateTime.toInstant())).setOverTime(Date.from(endDateTime.toInstant()))
                .setAddress(address).setId(id).setMerchantId(merchantId).setUrlId(!CommUtil.checkNull(urlId) ? UUIDUtil.getTimeId() : urlId);
        if (CommUtil.checkNull(banner) && banner.contains("base64")) {
            String activity = Base64Util.generateImage("activity/" + merchantActivity.getUrlId(), banner);
            if (CommUtil.checkNull(activity)) {
                merchantActivity.setBanner(activity);
            }
        }
        if (!merchantActivityService.saveOrUpdate(merchantActivity)) {
            return ReturnBody.error(ResultCodeInfo.SERVICE_EXCEPTION);
        }
        return ReturnBody.success();
    }

    @ApiOperation("活动详情")
    @PostMapping("detail")
    public String detail(Long id) {
        Long merchantId = (Long) request.getAttribute("id");
        MerchantActivity result = merchantActivityService.getByIdForUpdate(id);
        if (!CommUtil.checkNull(result)) {
            return ReturnBody.error("获取活动详情失败,请重试或联系管理员");
        }
        return ReturnBody.success(result);
    }

    @ApiOperation("删除活动")
    @PostMapping("delete")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = true),
    })
    @ParameterVerify(notNull = "id")
    public String delete(Long id) {
        Long merchantId = (Long) request.getAttribute("id");
        MerchantActivity merchantActivity = merchantActivityService.getByIdForUpdate(id);
        if (!CommUtil.checkNull(merchantActivity)) {
            return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
        }
        if (!merchantActivity.getMerchantId().equals(merchantId)) {
            return ReturnBody.error(ResultCodeInfo.NO_AUTHORITY_OPERATE_PERMISSION);
        }
        //是否有人报名
        int count = usActivityRegisterService.count(new QueryWrapper<UsActivityRegister>()
                .eq(UsActivityRegister.ACTIVITY_ID, merchantActivity.getId())
                .in(UsActivityRegister.STATUS, 0, 1, 2)
        );
        if (count != 0) {
            return ReturnBody.error("当前活动已有人报名,不可删除 !");
        }
        if (!merchantActivityService.removeById(id)) {
            return ReturnBody.error(ResultCodeInfo.SERVICE_EXCEPTION);
        }
        return ReturnBody.success();
    }

    @ApiOperation("获取报名活动人员列表")
    @PostMapping("registerPeopleList")
    public String registerPeopleList(PageInfo pageInfo, Integer sort, String createTimeScope) {
        Long merchantId = (Long) request.getAttribute("id");
        // 设置分页排序规则
        PageUtil.setPageSortRoles(pageInfo, sort, "create_time");
        //执行分页辅助工具
        PageResult<UsActivityRegister> pageResult = new PageUtil<UsActivityRegister>(pageInfo).startPage((page, queryWrapper) -> {
            queryWrapper.eq(UsActivityRegister.MERCHANT_ID, merchantId);
            if (CommUtil.checkNull(createTimeScope)) {
                List<String> list = JSON.parseArray(createTimeScope, String.class);
                queryWrapper.between(UsActivityRegister.CREATE_TIME, list.get(0), list.get(1));
            }
            usActivityRegisterService.page(page, queryWrapper);
        });
        pageResult.getList().forEach(item -> {
            UsInfo usInfo = usInfoService.getById(item.getUsId());
            if (usInfo != null) {
                item.setAvatar(usInfo.getAvatar());
                item.setNick(usInfo.getNick());
            }

            if (item.getActivityId() != null) {
                MerchantActivity activity = merchantActivityService.getOne(
                        new QueryWrapper<MerchantActivity>()
                                .eq(MerchantActivity.ID, item.getActivityId())
                                .eq(MerchantActivity.MERCHANT_ID, merchantId)
                );
                if (activity != null) {
                    item.setActivityTitle(activity.getTitle());
                }
            }
        });
        return ReturnBody.success(pageResult);
    }

    @ApiOperation("获取报名记录详情")
    @PostMapping("registerDetail")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "报名记录id", required = true),
    })
    public String registerDetail(Long id) {
        Long merchantId = (Long) request.getAttribute("id");

        // 获取报名信息
        UsActivityRegister registerInfo = usActivityRegisterService.getOne(
                new QueryWrapper<UsActivityRegister>()
                        .eq(UsActivityRegister.ID, id)
                        .eq(UsActivityRegister.MERCHANT_ID, merchantId)
        );
        if (registerInfo == null) {
            return ReturnBody.error("获取数据失败,请刷新重试 或 联系管理员");
        }
        RegisterPeopleDetailVO result = new RegisterPeopleDetailVO();
        result.setRecordId(registerInfo.getId().toString())
                .setRegistrationTime(String.valueOf(registerInfo.getCreateTime().getTime()))
                .setRegisterStatus(registerInfo.getStatus())
                .setOrderNum(registerInfo.getOrderNum());
        // 获取用户信息
        if (CommUtil.checkNull(registerInfo.getUsId())) {
            UsInfo usInfo = usInfoService.getById(registerInfo.getUsId());
            if (usInfo != null) {
                result.setAvatar(usInfo.getAvatar()).setNick(usInfo.getNick());
            }
        }
        // 获取活动信息
        if (CommUtil.checkNull(registerInfo.getActivityId())) {
            MerchantActivity activity = merchantActivityService.getOne(
                    new QueryWrapper<MerchantActivity>()
                            .eq(MerchantActivity.ID, registerInfo.getActivityId())
                            .eq(MerchantActivity.MERCHANT_ID, merchantId)
            );
            if (activity != null) {
                result.setActivityId(activity.getId().toString())
                        .setActivityTitle(activity.getTitle())
                        .setHasCost(activity.getHasCost())
                        .setCost(activity.getCost())
                        .setOpenTime(String.valueOf(activity.getOpenTime().getTime()))
                        .setOverTime(String.valueOf(activity.getOverTime().getTime()));
            }
        }
        return ReturnBody.success(result);
    }


    @ApiOperation("确认用户签到")
    @PostMapping("confirmSignIn")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "recodeId", value = "报名记录id", required = true),
            @ApiImplicitParam(paramType = "query", dataTypeClass = String.class, name = "orderNum", value = "订单号", required = true),
    })
    public String confirmSignIn(Long recodeId, String orderNum) {
        UsActivityRegister register = usActivityRegisterService.getOneForUpdate(
                new QueryWrapper<UsActivityRegister>()
                        .eq(UsActivityRegister.ID, recodeId)
                        .eq(UsActivityRegister.ORDER_NUM, orderNum)
        );
        if(register == null){
            return ReturnBody.error("请求失败 : 报名记录丢失");
        }
        MerchantActivity activity = merchantActivityService.getByIdForUpdate(register.getActivityId());
        if (activity == null){
            return ReturnBody.error("请求失败 : 活动记录丢失");
        }
        if (!merchantActivityService.activitiesIsInProgress(activity)) {
            return ReturnBody.error("请求失败 : 活动未开始或已经结束");
        }
        if (!usActivityRegisterService.updateById(register.setStatus(2))) {
            return ReturnBody.error("请求失败 : 设置状态失败");
        }
        return ReturnBody.success();
    }
}
